package com.jialanmo.helper.recyclerview;

import android.support.annotation.IdRes;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;

import com.jialanmo.helper.OnItemClickListener;

public final class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    private final SparseArray<View> mViews = new SparseArray<>();

    private final RecyclerView.Adapter mAdapter;
    private final OnItemClickListener mOnItemClickListener;

    public ViewHolder(ViewHolder viewHolder, RecyclerView.Adapter adapter) {
        this(viewHolder.itemView, adapter, viewHolder.mOnItemClickListener);
    }

    public ViewHolder(View itemView, RecyclerView.Adapter adapter, OnItemClickListener onItemClickListener) {
        super(itemView);
        mAdapter = adapter;
        mOnItemClickListener = onItemClickListener;
        if (onItemClickListener != null) {
            itemView.setOnClickListener(this);
        }
    }

    public <T extends View> T getView(@IdRes int viewId) {
        View view = mViews.get(viewId);
        if (view == null) {
            view = itemView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }

    @Override
    public void onClick(View v) {
        if (mAdapter instanceof HeaderAndFooterAdapter && ((HeaderAndFooterAdapter) mAdapter).hasHeaderView()) {
            if (((HeaderAndFooterAdapter) mAdapter).isHeaderView(getAdapterPosition())) {
                return;
            }
            mOnItemClickListener.onItemClick(getAdapterPosition() - 1);
            return;
        }
        if (mAdapter instanceof HeaderAndFooterAdapter && ((HeaderAndFooterAdapter) mAdapter).hasFooterView() && ((HeaderAndFooterAdapter) mAdapter).isFooterView(getAdapterPosition())) {
            return;
        }
        mOnItemClickListener.onItemClick(getAdapterPosition());
    }
}
